import { Captcha } from '@app/utils/captcha/interface/auth.dto';
import {
  Body,
  Controller,
  Get,
  Post,
  Request,
  UnauthorizedException,
  UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { AuthService } from './auth.service';
import { UserDto } from './dto/login.dto';

@ApiTags('后台权限模块')
@ApiBearerAuth()
@Controller('/admin/auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @ApiOperation({ summary: '获取验证码' })
  @Get('captcha')
  sendCaptcha(): Captcha {
    return this.authService.genCaptcha();
  }

  @ApiOperation({ summary: '用户登录' })
  @UseGuards(AuthGuard('admin'))
  @Post('login')
  async login(@Request() req, @Body() userDto: UserDto) {
    if (!userDto.captcha.text) {
      throw new UnauthorizedException('验证码为空');
    }
    if (!this.authService.checkCaptcha(userDto.captcha)) {
      throw new UnauthorizedException('验证码错误');
    }
    return this.authService.login(req.user);
  }

  @ApiOperation({ summary: '初始化管理员' })
  @Post('init')
  init() {
    return this.authService.init();
  }
}
